package com.wk.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wk.dao.CmfzAdminDao;
import com.wk.entity.CmfzAdmin;
import com.wk.service.CmfzShiroService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.security.Principal;
import java.util.Set;

public class MyAuthorRealm extends AuthorizingRealm {

    @Autowired
    private CmfzShiroService cmfzShiroService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //通过principal获取身份信息==主身份
        String username = principal.getPrimaryPrincipal().toString();
        //查询授权数据
        Set<String> roles = cmfzShiroService.selectRoleNameByUsername(username);
        Set<String> permissions = cmfzShiroService.selectPermissionByUsername(username);

        //封装返回info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }

    @Autowired
    private CmfzAdminDao cmfzAdminDao;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.获取用户名
        UsernamePasswordToken token1 = (UsernamePasswordToken) token;

        //2.查询数据库
        CmfzAdmin cmfzAdmin = cmfzAdminDao.selectOne(new QueryWrapper<CmfzAdmin>().eq("username", token1.getUsername()));

        //3.封装info
        if(cmfzAdmin!=null){
            //处理盐值
            ByteSource bytes = ByteSource.Util.bytes(cmfzAdmin.getSalt());

            return new SimpleAuthenticationInfo(cmfzAdmin.getUsername(), cmfzAdmin.getPassword(),bytes,this.getName());
        }


        return null;
    }
}
